-- Lua Battle System - AI行为调试工具
-- 提供可视化的AI决策过程调试和分析功能

local Logger = require("utils.logger")
local TableUtils = require("utils.table_utils")
local AIQualityAssessor = require("ai.ai_quality_assessor")

local AIDebugger = {
    -- 调试配置
    config = {
        enable_verbose_logging = true,
        max_debug_history = 1000,
        enable_step_by_step = false,
        enable_visualization = true,
        save_debug_files = true,
        debug_output_path = "debug/ai_debug/"
    },

    -- 调试状态
    debug_state = {
        is_debugging = false,
        current_step = 0,
        decision_trace = {},
        performance_trace = {},
        error_log = {}
    },

    -- 调试历史
    debug_history = {
        decisions = {},
        evaluations = {},
        performance_metrics = {},
        ai_states = {}
    },

    -- 质量评估器
    quality_assessor = nil
}

-- AI调试器构造函数
function AIDebugger:new(o)
    local o = o or {}
    setmetatable(o, self)
    self.__index = self
    o:init()
    return o
end

-- 初始化调试器
function AIDebugger:init()
    self.debug_state = {
        is_debugging = false,
        current_step = 0,
        decision_trace = {},
        performance_trace = {},
        error_log = {}
    }

    self.quality_assessor = AIQualityAssessor:new()

    -- 创建调试输出目录
    self:create_debug_directory()

    Logger.info("AI调试器初始化完成")
end

-- 创建调试目录
function AIDebugger:create_debug_directory()
    local mkdir_cmd = "mkdir -p " .. self.config.debug_output_path
    os.execute(mkdir_cmd)
end

-- 开始调试会话
function AIDebugger:start_debug_session(session_name)
    self.debug_state.is_debugging = true
    self.debug_state.current_step = 0
    self.debug_state.decision_trace = {}
    self.debug_state.performance_trace = {}

    local session_info = {
        name = session_name or "debug_session_" .. os.time(),
        start_time = os.time(),
        session_id = math.random(100000, 999999)
    }

    Logger.info("开始AI调试会话: " .. session_info.name)

    return session_info
end

-- 结束调试会话
function AIDebugger:end_debug_session(session_info)
    self.debug_state.is_debugging = false

    if session_info then
        session_info.end_time = os.time()
        session_info.duration = session_info.end_time - session_info.start_time

        -- 生成调试报告
        self:generate_debug_report(session_info)

        Logger.info("AI调试会话结束: " .. session_info.name .. " (耗时: " .. session_info.duration .. "秒)")
    end
end

-- 调试AI决策过程
function AIDebugger:debug_ai_decision(ai, character, battle_state, context)
    if not self.debug_state.is_debugging then
        return nil
    end

    self.debug_state.current_step = self.debug_state.current_step + 1

    -- 创建调试上下文
    local debug_context = {
        step = self.debug_state.current_step,
        timestamp = os.time(),
        ai = ai,
        character = character,
        battle_state = self:sanitize_battle_state(battle_state),
        context = context or {},
        decision_process = {}
    }

    -- 记录决策前的状态
    debug_context.pre_decision_state = {
        character_state = self:capture_character_state(character),
        battle_state = self:capture_battle_state(battle_state),
        ai_state = self:capture_ai_state(ai)
    }

    -- 开始性能监控
    local start_time = os.clock()

    -- 执行AI决策（带详细跟踪）
    local decision = self:trace_decision_execution(ai, character, battle_state, debug_context)

    -- 结束性能监控
    local end_time = os.clock()
    local execution_time = (end_time - start_time) * 1000

    -- 记录决策后的状态
    debug_context.post_decision_state = {
        character_state = self:capture_character_state(character),
        battle_state = self:capture_battle_state(battle_state)
    }

    -- 性能指标
    debug_context.performance = {
        execution_time_ms = execution_time,
        memory_usage_kb = collectgarbage("count"),
        step_number = self.debug_state.current_step
    }

    -- 质量评估
    debug_context.quality_assessment = self.quality_assessor:assess_decision_quality(
        character, battle_state, decision, context
    )

    -- 添加到调试历史
    self:add_to_debug_history(debug_context)

    -- 生成可视化输出
    if self.config.enable_visualization then
        self:generate_visualization(debug_context)
    end

    return {
        decision = decision,
        debug_context = debug_context
    }
end

-- 跟踪决策执行过程
function AIDebugger:trace_decision_execution(ai, character, battle_state, debug_context)
    local decision_process = debug_context.decision_process

    -- 记录决策开始
    table.insert(decision_process, {
        phase = "start",
        timestamp = os.clock(),
        description = "开始AI决策过程",
        data = {
            ai_type = ai.name or "unknown",
            character_id = character.id,
            character_name = character.name
        }
    })

    -- 如果是战术AI，记录决策树使用情况
    if ai.use_decision_tree and ai.decision_trees then
        table.insert(decision_process, {
            phase = "tree_selection",
            timestamp = os.clock(),
            description = "选择决策树",
            data = {
                health_percentage = character.hp / character.max_hp,
                use_attack_tree = character.hp / character.max_hp >= 0.3
            }
        })
    end

    -- 执行实际的AI决策
    local decision = ai:make_decision(character, battle_state)

    -- 记录决策结果
    table.insert(decision_process, {
        phase = "result",
        timestamp = os.clock(),
        description = "AI决策完成",
        data = {
            decision_type = decision and decision.type or "none",
            decision_score = decision and decision.score or 0,
            has_target = decision and decision.target ~= nil
        }
    })

    return decision
end

-- 捕获角色状态
function AIDebugger:capture_character_state(character)
    return {
        id = character.id,
        name = character.name,
        team_id = character.team_id,
        hp = character.hp,
        max_hp = character.max_hp,
        mp = character.mp,
        max_mp = character.max_mp,
        attack = character.attack,
        defense = character.defense,
        magic_attack = character.magic_attack,
        magic_defense = character.magic_defense,
        speed = character.speed,
        is_alive = character.is_alive,
        health_percentage = character.hp / character.max_hp,
        mp_percentage = character.mp / character.max_mp,
        skill_count = #character.skills,
        item_count = TableUtils.get_table_size(character.items or {})
    }
end

-- 捕获战斗状态
function AIDebugger:capture_battle_state(battle_state)
    local state = {
        current_turn = battle_state.current_turn,
        total_characters = #battle_state.characters,
        alive_characters = 0,
        player_team_size = 0,
        enemy_team_size = 0,
        teams = {}
    }

    for _, char in ipairs(battle_state.characters) do
        if char.is_alive then
            state.alive_characters = state.alive_characters + 1
        end

        if char.team_id == battle_state.player_team_id then
            state.player_team_size = state.player_team_size + 1
        else
            state.enemy_team_size = state.enemy_team_size + 1
        end

        -- 按队伍统计
        if not state.teams[char.team_id] then
            state.teams[char.team_id] = {
                total = 0,
                alive = 0,
                avg_health = 0
            }
        end

        state.teams[char.team_id].total = state.teams[char.team_id].total + 1
        if char.is_alive then
            state.teams[char.team_id].alive = state.teams[char.team_id].alive + 1
        end
    end

    -- 计算平均生命值
    for team_id, team_data in pairs(state.teams) do
        local total_health = 0
        local count = 0

        for _, char in ipairs(battle_state.characters) do
            if char.team_id == team_id then
                total_health = total_health + (char.hp / char.max_hp)
                count = count + 1
            end
        end

        team_data.avg_health = count > 0 and total_health / count or 0
    end

    return state
end

-- 捕获AI状态
function AIDebugger:capture_ai_state(ai)
    local state = {
        name = ai.name or "unknown",
        difficulty = ai.difficulty or "normal",
        use_decision_tree = ai.use_decision_tree or false
    }

    -- 如果是战术AI，记录战术参数
    if ai.tactics then
        state.tactics = ai.tactics
        state.tactic_weights = ai.tactic_weights
    end

    -- 记录决策树状态
    if ai.decision_trees then
        state.decision_trees = {}
        for tree_name, tree in pairs(ai.decision_trees) do
            if tree and tree.get_performance_report then
                state.decision_trees[tree_name] = tree:get_performance_report()
            end
        end
    end

    return state
end

-- 清理战斗状态（移除敏感数据）
function AIDebugger:sanitize_battle_state(battle_state)
    local sanitized = {
        characters = {},
        current_turn = battle_state.current_turn,
        player_team_id = battle_state.player_team_id
    }

    for _, char in ipairs(battle_state.characters) do
        table.insert(sanitized.characters, {
            id = char.id,
            name = char.name,
            team_id = char.team_id,
            hp = char.hp,
            max_hp = char.max_hp,
            mp = char.mp,
            max_mp = char.max_mp,
            attack = char.attack,
            defense = char.defense,
            is_alive = char.is_alive,
            skill_count = #char.skills
        })
    end

    return sanitized
end

-- 添加到调试历史
function AIDebugger:add_to_debug_history(debug_context)
    -- 添加决策历史
    table.insert(self.debug_history.decisions, debug_context)

    -- 添加性能历史
    table.insert(self.debug_history.performance_metrics, {
        step = debug_context.step,
        execution_time = debug_context.performance.execution_time_ms,
        memory_usage = debug_context.performance.memory_usage_kb,
        quality_score = debug_context.quality_assessment.overall_score
    })

    -- 保持历史记录在合理范围内
    if #self.debug_history.decisions > self.config.max_debug_history then
        table.remove(self.debug_history.decisions, 1)
    end

    if #self.debug_history.performance_metrics > self.config.max_debug_history then
        table.remove(self.debug_history.performance_metrics, 1)
    end
end

-- 生成可视化输出
function AIDebugger:generate_visualization(debug_context)
    local step = debug_context.step
    local filename = string.format("%sstep_%04d.html", self.config.debug_output_path, step)

    local html_content = self:generate_debug_html(debug_context)

    if self.config.save_debug_files then
        local file = io.open(filename, "w")
        if file then
            file:write(html_content)
            file:close()
        else
            Logger.warn("无法创建调试文件: " .. filename)
        end
    end
end

-- 生成调试HTML
function AIDebugger:generate_debug_html(debug_context)
    local context = debug_context

    return string.format([[
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI决策调试 - 步骤 %d</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { border-bottom: 2px solid #007cba; padding-bottom: 10px; margin-bottom: 20px; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .section h3 { color: #007cba; margin-top: 0; }
        .status-bar { display: flex; justify-content: space-between; margin: 10px 0; }
        .status-item { text-align: center; padding: 10px; background: #e9ecef; border-radius: 5px; min-width: 100px; }
        .process-step { margin: 10px 0; padding: 10px; border-left: 4px solid #28a745; background: #f8f9fa; }
        .decision-result { background: #d4edda; border: 1px solid #c3e6cb; padding: 10px; border-radius: 5px; }
        .quality-good { color: #155724; font-weight: bold; }
        .quality-warning { color: #856404; font-weight: bold; }
        .quality-bad { color: #721c24; font-weight: bold; }
        .stats-table { width: 100%%; border-collapse: collapse; margin: 10px 0; }
        .stats-table th, .stats-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        .stats-table th { background-color: #f2f2f2; }
        .health-bar { width: 100%%; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden; }
        .health-fill { height: 100%%; background: linear-gradient(to right, #dc3545, #ffc107, #28a745); }
        .timeline { position: relative; padding-left: 20px; }
        .timeline::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 2px; background: #007cba; }
        .timeline-item { position: relative; padding: 10px 0; }
        .timeline-item::before { content: ''; position: absolute; left: -24px; top: 15px; width: 8px; height: 8px; border-radius: 50%%; background: #007cba; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 AI决策调试分析</h1>
            <p><strong>步骤:</strong> %d | <strong>时间戳:</strong> %s</p>
        </div>

        <div class="section">
            <h3>📊 决策概览</h3>
            <div class="status-bar">
                <div class="status-item">
                    <strong>执行时间</strong><br>
                    %.2f ms
                </div>
                <div class="status-item">
                    <strong>内存使用</strong><br>
                    %.1f KB
                </div>
                <div class="status-item">
                    <strong>质量评分</strong><br>
                    <span class="%s">%.1f/100 (%s)</span>
                </div>
            </div>
        </div>

        <div class="section">
            <h3>🎭 角色状态</h3>
            <table class="stats-table">
                <tr>
                    <th>角色</th>
                    <th>生命值</th>
                    <th>魔法值</th>
                    <th>攻击力</th>
                    <th>防御力</th>
                    <th>状态</th>
                </tr>
                <tr>
                    <td>%s (Lv.%d)</td>
                    <td>
                        <div class="health-bar">
                            <div class="health-fill" style="width: %.1f%%;"></div>
                        </div>
                        %d/%d
                    </td>
                    <td>%d/%d</td>
                    <td>%d</td>
                    <td>%d</td>
                    <td>%s</td>
                </tr>
            </table>
        </div>

        <div class="section">
            <h3>⚔️ 战斗环境</h3>
            <table class="stats-table">
                <tr>
                    <th>队伍</th>
                    <th>存活/总数</th>
                    <th>平均生命值</th>
                    <th>状态</th>
                </tr>
                %s
            </table>
        </div>

        <div class="section">
            <h3>🔄 决策过程时间线</h3>
            <div class="timeline">
                %s
            </div>
        </div>

        <div class="section">
            <h3>🎯 最终决策</h3>
            <div class="decision-result">
                <strong>类型:</strong> %s<br>
                <strong>评分:</strong> %.1f<br>
                <strong>目标:</strong> %s<br>
                <strong>描述:</strong> %s
            </div>
        </div>

        <div class="section">
            <h3>📈 质量评估详情</h3>
            <table class="stats-table">
                <tr>
                    <th>评估维度</th>
                    <th>分数</th>
                    <th>评估</th>
                </tr>
                %s
            </table>
        </div>

        <div class="section">
            <h3>💡 改进建议</h3>
            <ul>
                %s
            </ul>
        </div>
    </div>
</body>
</html>
]],
        context.step,
        os.date("%Y-%m-%d %H:%M:%S", context.timestamp),
        context.performance.execution_time_ms,
        context.performance.memory_usage_kb,
        self:get_quality_class(context.quality_assessment.overall_score),
        context.quality_assessment.overall_score,
        context.quality_assessment.grade_description,
        context.pre_decision_state.character_state.name,
        context.character.id or 1,
        (context.pre_decision_state.character_state.health_percentage * 100),
        context.pre_decision_state.character_state.hp,
        context.pre_decision_state.character_state.max_hp,
        context.pre_decision_state.character_state.mp,
        context.pre_decision_state.character_state.max_mp,
        context.pre_decision_state.character_state.attack,
        context.pre_decision_state.character_state.defense,
        context.pre_decision_state.character_state.is_alive and "存活" or "死亡",
        self:generate_battle_state_table(context.pre_decision_state.battle_state),
        self:generate_decision_timeline(context.decision_process),
        context.decision and context.decision.type or "none",
        context.decision and (context.decision.score or 0) or 0,
        context.decision and context.decision.target and (context.decision.target.name or "无目标") or "无目标",
        context.quality_assessment.assessment or "无描述",
        self:generate_quality_assessment_table(context.quality_assessment),
        self:generate_recommendations_list(context.quality_assessment.recommendations)
    )
end

-- 获取质量等级样式类
function AIDebugger:get_quality_class(score)
    if score >= 80 then return "quality-good"
    elseif score >= 60 then return "quality-warning"
    else return "quality-bad"
    end
end

-- 生成战斗状态表格
function AIDebugger:generate_battle_state_table(battle_state)
    local rows = ""

    for team_id, team_data in pairs(battle_state.teams or {}) do
        local team_name = team_id == battle_state.player_team_id and "玩家队伍" or ("队伍" .. team_id)
        local status = team_data.alive > 0 and "战斗中" or "全灭"

        rows = rows .. string.format([[
                <tr>
                    <td>%s</td>
                    <td>%d/%d</td>
                    <td>%.1f%%</td>
                    <td>%s</td>
                </tr>
            ]], team_name, team_data.alive, team_data.total, team_data.avg_health * 100, status)
    end

    return rows
end

-- 生成决策过程时间线
function AIDebugger:generate_decision_timeline(decision_process)
    local items = ""

    for _, step in ipairs(decision_process) do
        items = items .. string.format([[
                <div class="timeline-item">
                    <strong>%s</strong>: %s
                </div>
            ]], step.phase, step.description)
    end

    return items
end

-- 生成质量评估表格
function AIDebugger:generate_quality_assessment_table(assessment)
    local rows = ""

    local dimensions = {
        {name = "战略正确性", result = assessment.details.strategic_correctness},
        {name = "效率性", result = assessment.details.efficiency},
        {name = "适应性", result = assessment.details.adaptability},
        {name = "资源管理", result = assessment.details.resource_management},
        {name = "风险评估", result = assessment.details.risk_assessment}
    }

    for _, dim in ipairs(dimensions) do
        if dim.result then
            rows = rows .. string.format([[
                    <tr>
                        <td>%s</td>
                        <td>%.1f</td>
                        <td>%s</td>
                    </tr>
                ]], dim.name, dim.result.score, dim.result.assessment or "")
        end
    end

    return rows
end

-- 生成建议列表
function AIDebugger:generate_recommendations_list(recommendations)
    local items = ""

    for _, recommendation in ipairs(recommendations or {}) do
        items = items .. "<li>" .. recommendation .. "</li>"
    end

    if items == "" then
        items = "<li>暂无改进建议</li>"
    end

    return items
end

-- 生成调试报告
function AIDebugger:generate_debug_report(session_info)
    local report_filename = string.format("%sdebug_report_%s_%d.html",
        self.config.debug_output_path, session_info.name, session_info.session_id)

    local html_content = self:generate_session_report(session_info)

    if self.config.save_debug_files then
        local file = io.open(report_filename, "w")
        if file then
            file:write(html_content)
            file:close()
            Logger.info("调试报告已生成: " .. report_filename)
        else
            Logger.warn("无法创建调试报告文件: " .. report_filename)
        end
    end
end

-- 生成会话报告
function AIDebugger:generate_session_report(session_info)
    local total_steps = #self.debug_history.decisions
    local avg_quality = 0
    local avg_execution_time = 0

    if total_steps > 0 then
        for _, decision in ipairs(self.debug_history.decisions) do
            avg_quality = avg_quality + decision.quality_assessment.overall_score
            avg_execution_time = avg_execution_time + decision.performance.execution_time_ms
        end
        avg_quality = avg_quality / total_steps
        avg_execution_time = avg_execution_time / total_steps
    end

    return string.format([[
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI调试会话报告 - %s</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { border-bottom: 2px solid #007cba; padding-bottom: 10px; margin-bottom: 20px; }
        .summary { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0; }
        .summary-card { background: #f8f9fa; padding: 15px; border-radius: 5px; text-align: center; }
        .summary-card h4 { margin: 0 0 10px 0; color: #007cba; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .step-list { list-style: none; padding: 0; }
        .step-item { margin: 10px 0; padding: 10px; background: #e9ecef; border-radius: 5px; cursor: pointer; }
        .step-item:hover { background: #dee2e6; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔍 AI调试会话报告</h1>
            <p><strong>会话名称:</strong> %s</p>
            <p><strong>会话ID:</strong> %d</p>
            <p><strong>开始时间:</strong> %s</p>
            <p><strong>持续时间:</strong> %d秒</p>
        </div>

        <div class="section">
            <h3>📊 会话统计</h3>
            <div class="summary">
                <div class="summary-card">
                    <h4>总决策数</h4>
                    <h2>%d</h2>
                </div>
                <div class="summary-card">
                    <h4>平均质量</h4>
                    <h2>%.1f</h2>
                </div>
                <div class="summary-card">
                    <h4>平均执行时间</h4>
                    <h2>%.2f ms</h2>
                </div>
                <div class="summary-card">
                    <h4>会话时长</h4>
                    <h2>%d秒</h2>
                </div>
            </div>
        </div>

        <div class="section">
            <h3>📝 决策历史</h3>
            <div class="step-list">
                %s
            </div>
        </div>
    </div>
</body>
</html>
]], session_info.name, session_info.name, session_info.session_id,
        os.date("%Y-%m-%d %H:%M:%S", session_info.start_time), session_info.duration,
        total_steps, avg_quality, avg_execution_time, session_info.duration,
        self:generate_step_list()
)
end

-- 生成步骤列表
function AIDebugger:generate_step_list()
    local items = ""

    for _, decision in ipairs(self.debug_history.decisions) do
        local quality_class = self:get_quality_class(decision.quality_assessment.overall_score)
        local time_str = os.date("%H:%M:%S", decision.timestamp)

        items = items .. string.format([[
                <div class="step-item" onclick="window.open('step_%04d.html', '_blank')">
                    <strong>步骤 %d</strong> - %s<br>
                    <span class="%s">质量: %.1f/100</span> |
                    执行时间: %.2f ms |
                    决策类型: %s
                </div>
            ]], decision.step, decision.step, time_str, quality_class,
            decision.quality_assessment.overall_score,
            decision.performance.execution_time_ms,
            decision.decision and decision.decision.type or "none")
    end

    return items
end

-- 获取性能分析报告
function AIDebugger:get_performance_analysis()
    local metrics = self.debug_history.performance_metrics
    local decisions = self.debug_history.decisions

    if #metrics == 0 then
        return {message = "暂无性能数据"}
    end

    -- 计算统计数据
    local total_time = 0
    local total_quality = 0
    local max_time = 0
    local min_time = math.huge
    local max_quality = 0
    local min_quality = math.huge

    for i, metric in ipairs(metrics) do
        total_time = total_time + metric.execution_time
        total_quality = total_quality + metric.quality_score
        max_time = math.max(max_time, metric.execution_time)
        min_time = math.min(min_time, metric.execution_time)
        max_quality = math.max(max_quality, metric.quality_score)
        min_quality = math.min(min_quality, metric.quality_score)
    end

    local avg_time = total_time / #metrics
    local avg_quality = total_quality / #metrics

    -- 分析决策类型分布
    local decision_types = {}
    for _, decision in ipairs(decisions) do
        local dtype = decision.decision and decision.decision.type or "none"
        decision_types[dtype] = (decision_types[dtype] or 0) + 1
    end

    return {
        total_decisions = #metrics,
        performance_stats = {
            average_time = avg_time,
            max_time = max_time,
            min_time = min_time,
            average_quality = avg_quality,
            max_quality = max_quality,
            min_quality = min_quality
        },
        decision_type_distribution = decision_types,
        recommendations = self:generate_performance_recommendations(avg_time, avg_quality)
    }
end

-- 生成性能改进建议
function AIDebugger:generate_performance_recommendations(avg_time, avg_quality)
    local recommendations = {}

    if avg_time > 50 then
        table.insert(recommendations, "平均决策时间较长，考虑优化决策算法")
    end

    if avg_quality < 70 then
        table.insert(recommendations, "决策质量有待提高，检查AI策略配置")
    end

    return recommendations
end

-- 清理调试数据
function AIDebugger:clear_debug_data()
    self.debug_history = {
        decisions = {},
        evaluations = {},
        performance_metrics = {},
        ai_states = {}
    }

    Logger.info("调试数据已清理")
end

-- 导出调试数据
function AIDebugger:export_debug_data(filename)
    filename = filename or ("debug_export_" .. os.time() .. ".json")

    local export_data = {
        export_time = os.time(),
        debug_history = self.debug_history,
        performance_analysis = self:get_performance_analysis()
    }

    -- 这里可以实现JSON序列化，简化处理
    Logger.info("调试数据导出完成: " .. filename)

    return export_data
end

-- 导出模块
return AIDebugger